package com.robcity.platform.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateInterceptor.class);
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        this.printRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        this.printResponse(response);
        return response;
    }

    /**
     * 请求日志
     */
    private void printRequest(HttpRequest request, byte[] body) {
        LOGGER.info("===> [RestTemplate request] method: {}, url: {}", request.getMethod(), request.getURI());
        LOGGER.info("===> [RestTemplate request] body: {}", new String(body, StandardCharsets.UTF_8));
    }

    /**
     * 响应日志
     */
    private void printResponse(ClientHttpResponse response) throws IOException {
        LOGGER.info("===> [RestTemplate response] status code : {}", response.getStatusCode());
        LOGGER.info("===> [RestTemplate response] body: {}", StreamUtils.copyToString(response.getBody(),StandardCharsets.UTF_8));
    }
}
